<script setup>
import { ref, nextTick } from "vue";
import AccountManage from "@/views/home/accountCenter/accountManage.vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import { message } from "ant-design-vue";
import store from "@/store/index";
import { computed } from "vue";
import { watch } from "vue";
import { detectOS } from '@/common/utils/atherUtils.js'

import FakeUserAgent from '@/common/ua/fake.js'

import {ReloadOutlined, InfoCircleOutlined} from '@ant-design/icons-vue'


const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [String, Number],
    default: "",
  },
  appKey: {
    type: String,
    default: "",
  },
});

let area = ref([]);
let country_id = ref();
let province_id = ref();
let city_id = ref();
const countryList = ref([]);
const provinceList = ref([]);
const cityList = ref([]);

// 是否使用代理
const useProxy = ref(false)

// 代理 构造函数
const useFakeUserAgent = ref()

// 系统类型
const system_type = ref()
// 浏览器版本
const browserVersion = ref('all')
// 浏览器版本列表
const browserVersionOptions = ref(Array.from({ length: 134 - 107 + 1 }, (_, i) => ({
  value: i + 107,
  label: i + 107
})))

browserVersionOptions.value.unshift({
  value: 'all',
  label: '全部' 
})

const UA = ref('')

let foreignKey = ['twitter','instagram','facebook']
let isForeignPlatform = computed(()=>{
  return foreignKey.includes(props.appKey)
})
const isDisabled = computed(() => {
  return (is_china)=>{
    if(!isForeignPlatform.value){
      return false
    }else if(isForeignPlatform.value&&!is_china){
      return false
    }else{
      return true
    }
  }
});

const getAllCountry = () => {
  let params = {
    level: 0,
    parent_id: 0,
  };
  return request
    .get("/work_ai", "/user/socialMedia/area/get", params)
    .then((res) => {
      countryList.value = res.result;
    });
};
const countryChange = (id)=>{
  province_id.value = null
  city_id.value = null
  getProvinceList(id)
}

const getProvinceList = (parent_id) => {
 
  if (!parent_id) {
    return;
  }
  let params = {
    level: 1,
    parent_id,
  };
  return request
    .get("/work_ai", "/user/socialMedia/area/get", params)
    .then((res) => {
      provinceList.value = res.result;
    });
};
const provinceChange = (id)=>{
   city_id.value = null
   getCityList(id)
}
const getCityList = (parent_id) => {
  if (!parent_id) {
    return;
  }
  let params = {
    level: 2,
    parent_id,
  };
  return request
    .get("/work_ai", "/user/socialMedia/area/get", params)
    .then((res) => {
      cityList.value = res.result;
      console.log(cityList.value,'cityList.value');
    });
};

const emit = defineEmits(["update:visible", "success"]);

let handleParams = ()=>{
  let params = {
    area:{}
  }
  let country = 'country'
  let province = 'province'
  let city = 'city'
  if(country_id.value){//国家
    let country = countryList.value.find(item=>item.id==country_id.value)
    params.area.country = country
  }
  if(province_id.value){//省份
    
    let province = provinceList.value.find(item=>item.id==province_id.value)
   
    params.area.province = province
  }
  if(city_id.value){//城市
    let city = cityList.value.find(item=>item.id==city_id.value)
    params.area.city= city
  }
  return params.area
}

const confirmLoading=  ref(false)

const onConfirmArea = async() => {
  if(!isForeignPlatform.value&&(!country_id.value||!province_id.value)){
    if(!country_id.value){
      return message.warning('请选择国家或地区')
    }
    if(!province_id.value){
      return message.warning('请选择省或州')
    }
  }

  if(isForeignPlatform.value&&!country_id.value){
    return message.warning('请选择国家或地区')
  }

  if (cityList.value.length && !city_id.value) {
    return message.warning("请选择城市");
  }

  if(props.id){
    editAccout();
    return
  }

  confirmLoading.value = true
  
  try {
    let area = handleParams();
    console.log(area, 'area');

    let proxy = ''
    let userAgent = ''
    // 如果开启了代理
    if (useProxy.value) {      
      const {result} = await request.post("/work_ai", "/platform/account/proxy/area", {area, refresh: 1, validate: 1})
      console.log(result,'account/proxy/area');
      proxy = `${result.protocol}${result.user}:${result.password}@${result.ip}:${result.port}` 
    }
    userAgent = UA.value
    console.log(proxy, userAgent, '收集到的参数');

    emit("success", {
      area,
      proxy,
      userAgent
    });

  } catch (error) {
    
  } finally {
    confirmLoading.value = false
  }



};
const editAccout = ()=>{
  let params = {
    id:props.id,
    area:{}
  }
 
  params.area = handleParams();

  request
    .put("/work_ai", "/user/platformAccount/user/update", {
      ...params
    })
    .then((res) => {
        emit("success");
        message.success("编辑成功");
    });
}
const onCancelArea = () => {
  emit("update:visible", false);
};
const getDetail = () => {
  request
    .get("/work_ai", "/user/platformAccount/user/info", {
      id: props.id,
    })
    .then(async (res) => {
      let area = res?.result?.area??[]
      if (area) {
        if (Array.isArray(area)) {
          return;
        }
        for(let key in area){
          if(key=='country'){
            country_id.value = area[key].id
            getProvinceList(area[key].id)
          }
          if(key=='province'){
            getCityList(area[key].id)
            province_id.value = area[key].id
          }

          if(key=='city'){
            city_id.value = area[key].id
          }
        }
      }
    });
};

watch(
  () => props.visible,
  async (val) => {
    if (val) {
      console.log(isForeignPlatform.value,'isForeignPlatform');
      getAllCountry();
      props.id && getDetail();
      // 获取系统信息
      const os = detectOS() 
      console.log(os, 'os');
      if (os == 'Windows') {
        system_type.value = 'Windows'
      } else if (os == 'MacOS') {
        system_type.value = 'Mac OS X'
      } else {
        system_type.value = ''
      }

      useFakeUserAgent.value = new FakeUserAgent({
        os,
        browsers: 'Chrome',
      })

      randomUa()
      console.log(useFakeUserAgent.value, 'useFakeUserAgent.value');
      
    } else {
      area.value = [];
      console.log(country_id.value,'country_id.value');
      country_id.value = null
      province_id.value = null
      city_id.value = null
      countryList.value = []
      provinceList.value = []
      cityList.value = []
    }
  }
);

// 随机 ua
const randomUa = () => {
  const ua = useFakeUserAgent.value.getBrowser('random')?.useragent
  UA.value = ua
  console.log(ua,'ua重新获取了');
}

// 浏览器版本号改变
const browserVersionChange = (val) => {
  console.log(val, 'browserVersionChangeval');
  if (browserVersion.value != 'all') {
    useFakeUserAgent.value.minVersion = val
  } else {
    useFakeUserAgent.value.minVersion = 0
  }
  console.log(useFakeUserAgent.value.minVersion,'useFakeUserAgent.value.minVersion');
  
  randomUa()
}

// 系统环境改变
const systemTypeChange = ({target}) => {
  console.log(target.value,'系统环境改变');
  useFakeUserAgent.value.os = target.value
  randomUa()
}

const filterOption = (input, option) => {
  return countryList.value.some((item) =>item.name.includes(input)&&option.value==item.id);
};
const provinceFilterOption = (input, option)=>{
  return provinceList.value.some((item) =>item.name.includes(input)&&option.value==item.id);
}
const cityFilterOption = (input, option)=>{
  return cityList.value.some((item) =>item.name.includes(input)&&option.value==item.id);
}
</script>

<template>
  <a-modal
    :visible="visible"
    title="账号环境"
    centered
    :width="950"
    @cancel="onCancelArea"
    @ok="onConfirmArea"
    :zIndex="1002"
    :destroyOnClose="true"
    :maskClosable="false"
    :confirm-loading="confirmLoading"
  >
    <div class="modal-content">

      <div class="system_box">

        <div class="system_item" v-if="props.appKey != 'tiktok'">
          <span>是否使用代理 
            <a-tooltip placement="top">
        <template #title>
          <span>如果是本地ip授权无需开启代理，异地登录开启代理，会导致绑定账号时会比较慢，请耐心等待</span>
        </template>
        <info-circle-outlined />
      </a-tooltip>
          </span> 
          <a-switch style="width: 50px;" v-model:checked="useProxy" checked-children="开" un-checked-children="关" />
          <span class="tips_class">如果是本地ip授权无需开启代理，异地登录开启代理，会导致绑定账号时会比较慢，请耐心等待</span>
        </div>

          <div class="system_item" v-if="props.appKey != 'tiktok'">
            <span>系统环境</span>
            <a-radio-group v-model:value="system_type" @change="systemTypeChange">
            <a-radio :value="'Mac OS X'">Mac OS X</a-radio>
            <a-radio :value="'Windows'">Windows</a-radio>
            </a-radio-group>
          </div>
  
          <div class="system_item" v-if="props.appKey != 'tiktok'">
            <span>Chrome浏览器版本</span>
            <div class="browser_version">
              <a-select
                v-model:value="browserVersion"
                style="width: 100px"
                placeholder="请选择浏览器版本"
                :options="browserVersionOptions"
                @change="browserVersionChange"
              ></a-select>
  
              <a-input class="input_content" v-model:value="UA" placeholder="随机UA信息">
                <template #suffix>
                  <span class="random" @click="randomUa"><ReloadOutlined /></span>
                </template>
              </a-input>
            </div>

            <span class="tips_class">建议选择自己浏览器相近的版本</span>
  
          </div>

        <div class="system_item">
        <div class="system_item_location">常用地区</div>
        <div class="region_box">
          <a-select
            style="width: 200px"
            placeholder="选择国家/地区"
            v-model:value="country_id"
            allowClear
            show-search
           :filter-option="filterOption"
            @change="countryChange(country_id)"
          >
            <a-select-option v-for="item in countryList" :disabled="isDisabled(item.is_china)" :value="item.id">
               {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
            style="width: 200px"
            show-search
            placeholder="选择省/州"
            v-model:value="province_id"
            :filter-option="provinceFilterOption"
            allowClear
            @change="provinceChange(province_id)"
          >
            <a-select-option  v-for="item in provinceList" :value="item.id">
              <span>
                {{ item.name ? item.name : "不限省/州" }}
              </span>
            </a-select-option>
          </a-select>
          <a-select
            style="width: 200px"
            show-search
            placeholder="选择城市"
            :filter-option="cityFilterOption"
            v-model:value="city_id"
            allowClear
          >
          <!-- :disabled="isDisabled(item.is_china)" 
          :class="item.name ? '' : 'gray'" 
          -->
            <a-select-option :disabled="isDisabled(item.is_china)" v-for="item in cityList"  :value="item.id">
              <span>
                {{ item.name ? item.name : "不限市" }}
              </span>
            </a-select-option>
          </a-select>
        </div>
      </div>

      </div>



  
      
    </div>
  </a-modal>
</template>

<style lang="less" scoped>

.tips_class{
  font-size: 12px;
  color: #999;
}

.modal-content {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;

  .region_box{
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }

  .system_box{
    display: flex;
  flex-direction: column;
gap: 30px;

  }

  .system_item{
     display: flex;
    flex-direction: column;
     gap: 5px;
     .browser_version{
      display: flex;
      align-items: center;
      gap: 10px;
      .input_content{
        flex: 1;
        .random{
          color: #1890ff;
          cursor: pointer;
          font-size: 18px;

        }
      }
     }
    }

    .system_item_location{
      &::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 4px;
      }
    }
}

.app-item {
  cursor: pointer;
}

.app-item-img {
  display: flex;
  width: 50px;
  height: 50px;
}

.app-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 5px;
}

.app-item-txt {
  display: flex;
  justify-content: center;
  line-height: 40px;
}
</style>

<style lang="less">
.account-modal .ss-modal-body {
  padding: 0;
}

.account-modal .ss-modal-content {
  height: 100%;

  .ss-modal-body {
    height: 100%;
  }
}

.download-modal {
  .down-list {
    display: flex;
    flex-flow: row;
    justify-content: space-around;
    height: 148px;
    width: 100%;
    margin-top: 20px;
    padding: 0 20px;

    .down-item {
      -webkit-user-select: none;
      -moz-user-select: none;
      user-select: none;
      cursor: pointer;
      box-shadow: 0 2px 16px rgba(28, 76, 186, 0.08);
      text-align: center;
      width: 148px;
      height: 148px;
      border-radius: 4px;

      > a {
        width: 100%;
        height: 100%;
        padding: 24px 0;
        display: inline-block;
      }

      div {
        padding-bottom: 12px;
      }
    }
  }
}
.gray {
  color: #bfbfbf;
}
</style>
